import React, { Component, createRef } from 'react'
import Captcha from "../../components/Captcha"
// ant导入
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined,KeyOutlined } from '@ant-design/icons';
// 导入请求资源
import url from "../../config/url"
import req from "../../http/req"
import { withRouter } from 'react-router-dom';
// css资源导入
import "./PasswdLogin.css"


class Passwdlogin extends Component {
  constructor(props) {
    super(props);
    this.capRef = createRef();
  }
  state={}
  
  render() {
    return (
      <>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{}}
          onFinish={this.onFinish}
        >
          {/* 用户名 */}
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入正确的用户名 !',
              },
            ]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
          </Form.Item>
          {/* 密码 */}
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: '请输入正确的密码 !',
              },
            ]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item
            name="captcha"
            rules={[
              {
                required: true,
                message: '请输入验证码 !',
              },
            ]}
          >
            <div className="captcha">
              <Input prefix={<KeyOutlined className="site-form-item-icon" />} type="text" placeholder="验证码" />
              <Captcha setKey = {this.getKey} ref={this.capRef} />
            </div>
            

          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登 录
            </Button>
          </Form.Item>
        </Form>
      </>
    )
  }
  // 提交处理程序
  onFinish = (values) => {
    // 将state中key值补录到values中
    values.key = this.state.key;
    // 发送请求
    req.post(url.PasswdLogin, values).then((res) => {
      if (res.data.errNo === 0) {
        // 没错
        message.success("登录成功！", 2, () => {
          this.props.history.push("/dashboard");
        });
      }else{
        // 错误
        message.error(res.data.errText, 2, () => {
          // 刷新验证码
          this.capRef.current.loadCaptcha();
        });
      }
    });
  };

  // 获取验证码key值的方法
  getKey = (key) => {
    this.setState({
      key,
    });
  };
}

export default withRouter(Passwdlogin);
